package auth

import (
	"context"

	v1 "gitee.com/liuxuezhan/ar-platform/rpc-client/authRoleClient/api/role/v1"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateRoleMenuInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewCreateRoleMenuInfoLogic 创建角色菜单权限（菜单应该通过权限操作赋权，且只能当前业务限制权限标识唯一才能使用，不希望调用该接口）
func NewCreateRoleMenuInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateRoleMenuInfoLogic {
	return &CreateRoleMenuInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateRoleMenuInfoLogic) CreateRoleMenuInfo(req *types.CreateRoleMenuInfoRequest) error {
	// 创建角色
	role, err := l.svcCtx.AuthRoleRpc.CreateRole(l.ctx, &v1.CreateRoleRequest{
		RolePid:     req.RolePid,
		RoleName:    req.RoleName,
		Description: req.Description,
		Remark:      req.Remark,
		ListOrder:   req.ListOrder,
		Status:      v1.Status(req.Status),
	})
	if err != nil {
		return err
	}

	// 创建权限
	permission, err := l.svcCtx.AuthRoleRpc.CreatePermission(l.ctx, &v1.CreatePermissionRequest{
		PermissionName:       role.GetRoleName() + "-菜单权限",
		PermissionIdentifier: PerIdentMenu,
		Status:               v1.Status_StatusNormal,
	})
	if err != nil {
		return err
	}

	// 创建角色和权限的关联关系
	if _, err = l.svcCtx.AuthRoleRpc.UpdateRolePermissions(l.ctx, &v1.UpdateRolePermissionsRequest{
		RoleId:        role.GetId(),
		PermissionIds: []int64{permission.Id},
	}); err != nil {
		return err
	}

	// 创建菜单的权限
	if _, err = l.svcCtx.AuthRoleRpc.UpdatePermissionFunctions(l.ctx, &v1.UpdatePermissionFunctionsRequest{
		PermissionId: permission.GetId(),
		FunctionIds:  req.MenuIds,
	}); err != nil {
		return err
	}

	return nil
}
